package com.ocn.li.scmdy.common.utils;

import java.security.MessageDigest;
import java.util.Random;

/**
 * @类： <code>Encrypt.java</code>
 * @描述：密码加密类
 * @版权所有：
 * @author： songwx
 * @version： V1, 2014-4-20 下午07:29:07
 */
public class Encrypt {
	private static Random randGen = null;
	private static char[] numbersAndLetters = null;
	 public static final String LETTER_UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	 /**取指定长度的随机字母字符串
	  * @param length 限定长度
	  * @return 指定长度的随机字母字符串
	  */
	 public static final String randomString(int length) {		        
		 if (length < 1) {		            
			 return null;		        
			 }		         
		 if (randGen == null) {		             
			 randGen = new Random();		              
			 numbersAndLetters = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();         
		 	}
			 char [] randBuffer = new char[length];		        
			 for (int i=0; i<randBuffer.length; i++) {		            
				 randBuffer[i] = numbersAndLetters[randGen.nextInt(25)];	       
				 }		        
			 	return new String(randBuffer);				 
	 }

	/**
	 * 
	 * @MethodName MD5
	 * @Description MD5加密密码
	 * @author zzy
	 * @param s
	 * @return
	 * @Return String
	 */
	public final static String MD5(String s) { 
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 
		'a', 'b', 'c', 'd', 'e', 'f' }; 
		try { 
		   byte[] strTemp = s.getBytes(); 
		   //使用MD5创建MessageDigest对象 
		   MessageDigest mdTemp = MessageDigest.getInstance("MD5"); 
		   mdTemp.update(strTemp); 
		   byte[] md = mdTemp.digest(); 
		   int j = md.length; 
		   char str[] = new char[j * 2]; 
		   int k = 0; 
		   for (int i = 0; i < j; i++) { 
		    byte b = md[i]; 
		    //System.out.println((int)b); 
		    //将没个数(int)b进行双字节加密 
		    str[k++] = hexDigits[b >> 4 & 0xf]; 
		    str[k++] = hexDigits[b & 0xf]; 
		   } 
		   return new String(str); 
		} catch (Exception e) {return null;} 
		} 
	/**
	 * 
	 * @MethodName MD5_pass
	 * @Description 组合密码
	 * @author zzy
	 * @param pass
	 * @return
	 * @Return String
	 */
	public static String MD5_pass(String pass){
		String s=MD5(pass).substring(0,20)+randomString(8);
		return s;
	}
	/**
	 * 
	 * @MethodName checkpass
	 * @Description 验证密码
	 * @author zzy
	 * @param password
	 * @param dbpass
	 * @return
	 * @Return boolean
	 */
	public static boolean checkpass(String password,String dbpass){
		String md5pass=MD5(password).substring(0,20);
        return dbpass.substring(0, dbpass.length() - 8).equals(md5pass);
	}
	
	public static void main (String []ff){
		System.out.println(MD5_pass("wujiabao"));
	}
}
